package leetcode.秋招.字节跳动.字节研发在线编程;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/7/25 17:34
 * @description：https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3?tpId=190&&tqId=35337&rp=1&ru=/activity/oj&qru=/ta/job-code-high-rd/question-ranking
 */
public class NC15求二叉树的层序遍历 {
    @Test
    public void test() {
        Solution solution = new Solution();
    }


    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    }


    public class Solution {
        /**
         *
         * @param root TreeNode类
         * @return int整型ArrayList<ArrayList<>>
         */
        public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
            // write code here
            ArrayList<ArrayList<Integer>> res = new ArrayList<>();
            if (root == null) return res;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                ArrayList<Integer> sub = new ArrayList<>();
                while (size > 0) {
                    TreeNode cur = queue.poll();
                    sub.add(cur.val);
                    if (cur.left != null)
                        queue.offer(cur.left);
                    if (cur.right != null)
                        queue.offer(cur.right);
                    size--;
                }
                res.add(sub);
            }
            return res;
        }
    }
}
